<template>
  <div class="bigbox">
    <!-- 表头盒子 -->
    <div class="leftbox">
      <!-- 树节点过滤 -->
      <div>
        <el-input
          placeholder="输入关键字进行过滤"
          size="small"
          v-model="filterText"
        >
        </el-input>
      </div>
      <!-- 树组件 -->
      <div style="margin-top: 15px">
        <el-tree
          ref="tree"
          :props="props"
          :data="treeList"
          :highlight-current="true"
          :current-node-key="nodeList?.id"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          node-key="id"
          :filter-node-method="filterNode"
          :load="loadNode"
          lazy
        >
          <span slot-scope="{ node, data }" class="slot-t-node">
            <template>
              <img
                class="node-img"
                v-if="data.bizOrgType == '03' || data.bizOrgType == '30'"
                src="@/assets/node0.png"
              />
              <img
                class="node-img"
                v-if="data.bizOrgType == '04' || data.bizOrgType == '40'"
                src="@/assets/node1.png"
              />
              <span :style="{ 'font-size': '14px' }">{{ node.label }}</span>
            </template>
          </span>
        </el-tree>
      </div>
    </div>
    <!-- 盒子主体 -->
    <div class="mainbox" v-loading="loading">
      <div class="top">
        <el-form
          :model="form"
          ref="form"
          label-position="left"
          label-width="80px"
          onsubmit="return false"
        >
          <el-row :gutter="20">
            <el-col :span="10" style="margin-top: 4px; display: flex">
              <el-radio-group
                size="small"
                v-model="radio"
                style="display: flex; margin-right: 20px"
                @input="changeType"
              >
                <el-radio-button label="月"></el-radio-button>
                <el-radio-button label="年"></el-radio-button>
              </el-radio-group>
              <el-date-picker
                v-model="time1"
                :type="timeType ? 'month' : 'year'"
                :placeholder="timeType ? '选择开始月份' : '选择开始年份'"
              >
              </el-date-picker>
              <div
                style="
                  height: 100%;
                  line-height: 35px;
                  margin: 0 5px;
                  font-size: 14px;
                  color: #606266;
                "
              >
                至
              </div>
              <el-date-picker
                v-model="time2"
                :type="timeType ? 'month' : 'year'"
                :placeholder="timeType ? '选择结束月份' : '选择结束年份'"
              >
              </el-date-picker>
            </el-col>
            <el-col :span="14" style="text-align: right">
              <el-form-item>
                <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- <div class="timeSearch">
          <div style="width: 400px"></div>
          <el-date-picker
            v-model="time1"
            :type="timeType ? 'month' : 'year'"
            :placeholder="timeType ? '选择开始月份' : '选择开始年份'"
          >
          </el-date-picker>
          <span style="margin: 0 20px; font-size: 14px; color: #606266"
            >至</span
          >
          <el-date-picker
            v-model="time2"
            :type="timeType ? 'month' : 'year'"
            :placeholder="timeType ? '选择结束月份' : '选择结束年份'"
          >
          </el-date-picker>
        </div> -->
        <!-- <div class="towBtn">
          <button @click="chongzhi" class="button">重置</button>
          <button @click="chaxun" class="button chaxun">查询</button>
        </div> -->
      </div>
      <div class="bodybox">
        <!-- 新增按钮 -->
        <!-- 循环图片盒子 -->
        <div class="formbox">
          <!-- 新增 -->
          <div class="littlebox">
            <div class="containC" @click="submit('add')">
              <i class="el-icon-plus"></i>
              <div style="color: #3b8eea; margin-top: 20px">新增报告</div>
            </div>
          </div>
          <div class="littlebox" v-for="item in entity" :key="item.id">
            <div class="timeTitle">{{ item.dateString }}</div>
            <!-- <div class="boxbtn">
              <el-button
                @click="xiazai(item)"
                type="text"
                style="color: black; font-size: 20px"
                ><i class="el-icon-download"></i
              ></el-button>
            </div> -->
            <div class="contain">
              <div style="color: #001bf9">
                {{ '设备运行分析报告' }}
              </div>
              <div class="imageBox" @click="toReport(item)">
                <img src="@/assets/iconPark-file-pdf 1.svg" alt="" />
                <div class="title" :style="{ fontSize: '18px' }">
                  {{ item.companyName }}
                </div>
              </div>
              <div class="bottomBtn">
                <!-- 查看 -->
                <el-button
                  type="text"
                  @click="toReport(item)"
                  style="color: green; font-size: 20px"
                  ><i class="el-icon-view"></i
                ></el-button>
                <!-- <el-button
                  type="text"
                  style="color: #4095e5; font-size: 20px"
                  @click="edit(item)"
                  ><i class="el-icon-edit"></i
                ></el-button> -->
                <el-button
                  type="text"
                  style="color: red; font-size: 20px"
                  @click="del(item.id)"
                  ><i class="el-icon-delete"></i
                ></el-button>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :current-page.sync="pageobj._pageNo"
              @current-change="chaxun"
              :total="total"
            >
            </el-pagination>
          </div> -->
        <!-- 新增/修改弹框 -->
        <el-dialog
          :show-close="false"
          :visible.sync="dialogVisible"
          width="500px"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :center="true"
        >
          <div class="dialog">
            <!-- 企业下拉 -->
            <el-form
              ref="dialogForm"
              :rules="rules"
              :model="dialogForm"
              label-width="110px"
            >
              <el-form-item label="报告类型:">
                <el-input
                  :value="timeType ? '月度运行分析报告' : '年度运行分析报告'"
                  disabled
                ></el-input>
              </el-form-item>
              <el-form-item label="企业" prop="companyName">
                <el-input disabled v-model="dialogForm.companyName"></el-input>
              </el-form-item>
              <el-form-item
                :label="timeType ? '月份：' : '年份：'"
                prop="dateString"
              >
                <el-date-picker
                  v-model="dialogForm.dateString"
                  :type="timeType ? 'month' : 'year'"
                  :placeholder="timeType ? '请选择月份' : '请选择年份'"
                  :format="timeType ? 'yyyy-MM' : 'yyyy'"
                  :value-format="timeType ? 'yyyy-MM' : 'yyyy'"
                >
                </el-date-picker>
              </el-form-item>
              <!-- <el-form-item label="生成时间">
                  <el-date-picker
                    v-model="this.dialogForm.dateString"
                    :default-value="new Date()"
                    type="datetime"
                    placeholder="选择日期时间"
                  >
                  </el-date-picker>
                </el-form-item> -->
            </el-form>
            <!-- 弹窗内容 -->
          </div>
          <div style="margin-top: 10px; text-align: center">
            <el-button @click="quxiao"> 取 消 </el-button>
            <el-button @click="sure" type="primary"> 确 定 </el-button>
          </div>
        </el-dialog>
        <el-dialog
          :visible.sync="viewVisible"
          width="1500px"
          v-if="viewVisible"
          :close-on-click-modal="false"
          :destroy-on-close="true"
          :center="true"
        >
          <ViewReport :data="mItem" />
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { saveMonReportApi, saveYearReportApi } from '@/api/monReport'
import dayjs from 'dayjs'
// import MReportDia from '@/views/Report/components/mReportDia.vue'
// import YReportDia from '@/views/Report/components/yReportDia.vue'
import axios from 'axios'
import download from 'downloadjs'
import ViewReport from './components/ViewReport'
// import YReport from '@/views/Report/components/YReport'
import {
  addReportApi,
  delReportApi,
  getEnergyTreeApi,
  getReportDataApi,
  getReportPageApi
} from '@/api/energy-consumption/Equipment-energy/Operation-analysis'
export default {
  name: 'monReportIndex',
  components: { ViewReport },
  data() {
    return {
      radio: '月',
      orgNo: '',
      time1: this.timeType
        ? new Date(new Date().getFullYear(), 0)
        : new Date(new Date().getFullYear(), 0, 1),
      time2: this.timeType
        ? new Date(new Date().getFullYear(), 11, 31)
        : new Date(new Date().getFullYear(), 11, 31),
      timeType: true,
      value1: new Date(),
      mItem: {},
      yItem: {},
      loading: false,
      entity: [],
      viewVisible: false,
      yVisible: false,
      options: [],
      filterText: '',
      dialogForm: {},
      formItem: {},
      treeList: [],
      nodeList: {},
      rules: {
        dateString: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ]
      },
      props: {
        label: 'bizOrgName',
        disabled: 'disabled'
      },
      dialogVisible: false,
      dialogVisibleM: false,
      dialogVisibleY: false,
      isedit: 'add',
      pageobj: {
        _pageNo: 0,
        _pageSize: 20
      },
      total: 0
    }
  },
  created() {},
  async mounted() {
    setTimeout(async () => {
      const res = await getEnergyTreeApi('')
      this.refreshNode(res?.data.list[0])
    }, 400)
  },

  methods: {
    // 初始化
    chushihua() {
      this.entity = []
      this.time1 = this.timeType
        ? new Date(new Date().getFullYear(), 0)
        : new Date(new Date().getFullYear(), 0, 1)
      this.time2 = this.timeType
        ? new Date(new Date().getFullYear(), 11, 31)
        : new Date(new Date().getFullYear(), 11, 31)
    },
    // 切换当前月/年
    async changeType(cb) {
      // const res = await getEnergyTreeApi('')
      // console.log('1', res)
      // this.orgNo = res.data.list[0].bizOrgNo
      if (cb === '月') {
        this.timeType = true
        this.chushihua()
        this.chaxun()
      } else if (cb === '年') {
        this.timeType = false
        this.chushihua()
        this.chaxun()
      }
    },
    // 查询分页信息
    async chaxun() {
      const startTime = this.timeType
        ? dayjs(this.time1).format('YYYY-MM')
        : dayjs(this.time1).format('YYYY')
      const endTime = this.timeType
        ? dayjs(this.time2).format('YYYY-MM')
        : dayjs(this.time2).format('YYYY')
      if (!this.time1 || !this.time2) return this.$message.error('请选择时间')
      if (this.orgNo) {
        try {
          this.loading = true
          const res = await getReportPageApi({
            dateType: this.timeType ? 1 : 2,
            pageNo: this.pageobj._pageNo,
            pageSize: this.pageobj._pageSize,
            orgNo: this.orgNo,
            startDate: startTime,
            endDate: endTime
          })
          this.entity = res?.data.list
        } catch (e) {
        } finally {
          this.loading = false
        }
      } else {
        this.$message.error('请选择企业')
      }
    },
    // 新增/修改
    submit(val) {
      this.isedit = val
      console.log(this.dialogForm.companyId)
      if (!this.dialogForm.companyId) {
        return this.$message.warning('请选择企业')
      }
      this.$set(
        this.dialogForm,
        'dateString',
        dayjs().format(this.timeType ? 'YYYY-MM' : 'YYYY')
      )
      this.dialogVisible = true
    },
    //  取消/弹框关闭
    quxiao() {
      this.dialogVisible = false
      if (this.isedit === 'add') {
        this.$refs.dialogForm.resetFields()
      } else {
        this.dialogForm = {
          orgName: this.orgName,
          orgNo: this.orgNo
        }
      }
    },
    // 确认修改并保存
    async sure() {
      await this.$refs.dialogForm.validate()
      // if (this.dialogForm.id) {
      //   const res = await updataSMSListApi(this.dialogForm)
      // } else {
      //   const res = await saveSMSListApi(this.dialogForm)
      // }
      const res = await addReportApi({
        companyId: this.nodeList.companyId,
        companyName: this.nodeList.bizOrgName,
        dateString: this.dialogForm.dateString,
        dateType: this.timeType ? '1' : '2',
        manageNo: this.nodeList.bizManageNo,
        orgNo: this.nodeList.bizOrgNo
      })
      if (res.code === 200) {
        this.$message.success('初始化生成成功')
        this.dialogVisible = false
        this.$refs.dialogForm.resetFields()
        await this.chaxun()
      } else {
        this.$message.error(res.message)
      }
    },
    // 删除头像
    // 树节点点击
    async handleNodeClick(val) {
      this.nodeList = val
      this.$set(this.dialogForm, 'orgName', this.nodeList.bizOrgName)
      this.$set(this.dialogForm, 'orgNo', this.nodeList.bizOrgNo)
      this.$set(this.dialogForm, 'companyId', this.nodeList.companyId)
      this.$set(this.dialogForm, 'companyName', this.nodeList.bizOrgName)
      this.orgNo = val.bizOrgNo
      this.orgName = val.bizOrgName
      if (this.time1 && this.time2) {
        this.chaxun()
      }
    },
    refreshNode(key) {
      console.log(key)
      // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
      const node = this.$refs.tree.getNode(key)
      //  设置未进行懒加载状态
      console.log('loaded', node)
      node.loaded = false
      // 重新展开节点就会间接重新触发load达到刷新效果
      this.$refs.tree.setCurrentKey(key)
      node.expand()
      this.nodeList = node.data
      this.$set(this.dialogForm, 'orgName', this.nodeList.bizOrgName)
      this.$set(this.dialogForm, 'orgNo', this.nodeList.bizOrgNo)
      this.$set(this.dialogForm, 'companyId', this.nodeList.companyId)
      this.orgNo = this.nodeList.bizOrgNo
      this.orgName = this.nodeList.bizOrgName
      console.log('nn', this.nodeList)
    },
    // 树组件懒加载
    async loadNode(node, resolve) {
      const res = await getEnergyTreeApi('')
      console.log(res)
      if (!this.orgNo) {
        this.orgNo = res?.data.list[0].bizOrgNo
        await this.chaxun()
      }

      if (node.level === 0) {
        // 初始的级数（最顶层）
        return resolve(res?.data.list) // 最顶层数据渲染为region
      } else if (node.level > 0) {
        const ress = await getEnergyTreeApi(node.data.bizOrgNo)
        return resolve(ress?.data.list)
      } else {
        return resolve([])
      }
    },
    // 树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.bizOrgName.indexOf(value) !== -1
    },
    // 编辑
    edit(item) {
      this.isedit = 'edit'
      this.formItem = { ...item }
      if (this.timeType) {
        this.dialogVisibleM = true
      } else {
        this.dialogVisibleY = true
      }
      console.log(item)
      // this.dialogForm = { ...item }
    },
    async editSubmit(item) {
      console.log('11', item)
      try {
        const res = this.timeType
          ? await saveMonReportApi(item)
          : await saveYearReportApi(item)
        if (res.code == 200) {
          this.$message.success('更新成功')
          this.dialogVisibleM = false
          this.dialogVisibleY = false
        } else {
          this.$message.error(res.message)
        }
        console.log(res)
      } catch (e) {
      } finally {
        this.chaxun()
      }
    },
    async chongzhi() {
      this.chushihua()
      this.chaxun()
    },
    // 删除
    async del(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该分析报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await delReportApi(id)
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          } catch (e) {
            console.log(e)
          } finally {
            this.chaxun()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async xiazai(item) {
      await axios({
        method: 'post',
        url: this.timeType
          ? '/biz/pio-microservice-biz/pio/month-ele-diagnostic/download/pdf'
          : '/biz/pio-microservice-biz/pio/year-ele-diagnostic/download/pdf',
        params: {
          id: item.id
        },
        responseType: 'blob'
      }).then((res) => {
        const blob = new Blob([res.data], { type: 'application/pdf' })
        download(
          blob,
          `${item.customerName}${
            this.timeType ? item.month : item.year
          }用电诊断报告.pdf`
        )
      })
    },
    async toReport(item) {
      const res = await getReportDataApi({ id: item.id })
      console.log('报告', res)
      this.mItem = { ...res.data.entity, id: item.id }
      this.viewVisible = true
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  }
}
</script>

<style lang="scss" scoped>
.bigbox {
  background-color: #f1f1f1;
  min-height: 100%;
  padding: 10px;
  display: flex;
  .leftbox {
    width: 300px;
    background-color: #fff;
    padding: 20px;
  }
  .mainbox {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    .top {
      background-color: #fff;
      padding: 20px;
      box-sizing: border-box;
      height: 80px !important;
      width: 100% !important;
      margin-bottom: 10px;
      .timeSearch {
        display: flex;
        align-items: center;
        width: 600px;
      }
    }
    .bodybox {
      position: relative;
      background-color: #fff;
      padding: 20px;
      padding-bottom: 40px;
      height: 100%;
      // .pagination {
      //   position: absolute;
      //   right:7%;
      //   bottom: 15px;
      // }
      .formbox {
        margin-top: 10px;
        display: flex;
        flex-wrap: wrap;
        .littlebox {
          position: relative;
          margin-right: 20px;
          margin-bottom: 10px;
          width: 275px;
          height: 350px;
          border: 1px solid #1890ff;
          border-radius: 3px;
          padding: 10px;
          .boxbtn {
            position: absolute;
            top: 10px;
            right: 20px;
          }
          .contain {
            .imageBox {
              width: 100%;
              text-align: center;
              img {
                cursor: pointer;
                margin-bottom: 40px;
              }
            }
            .bottomBtn {
              display: flex;
              justify-content: space-around;
              margin-top: 20px;
              font-size: 18px;
            }
          }
          .containC {
            text-align: center;
            padding-top: 40px;
            cursor: pointer;
            .el-icon-plus {
              font-size: 180px;
              color: #4095e5;
              text-align: center;
            }
          }
        }
      }
      .dialog {
        .title {
          font-size: 28px;
          margin-bottom: 30px;
        }
        .text {
          font-size: 12px;
          color: #3b8eea;
        }
      }
    }
  }
}

::v-deep .el-input {
  height: 32px;
}
::v-deep .el-input__inner {
  height: 32px;
}
::v-deep .el-input__icon {
  line-height: 1;
}
.el-select-dropdown__item {
  padding-left: 10px;
}
::v-deep .el-date-editor {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

::v-deep .el-range-separator {
  line-height: 25px;
}
.timeTitle {
  height: 50px;
}

.node-img {
  vertical-align: middle;
  margin-right: 4px;
}
</style>
